# @Time : 2020/8/17 11:34
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np


def get_linear_fit_k_b(pointsMat):
    # output 返回的四个值,前两个值是方向向量的x坐标,y坐标. 后面两个值是直线上的一个点.
    outPut = cv.fitLine(pointsMat, cv.DIST_L2, 0, 0.01, 0.01)
    k = outPut[1] / outPut[0]
    b = outPut[3] - k * outPut[2]
    return k, b


if __name__ == '__main__':
    imgColor = np.zeros((500, 500, 3), dtype=np.uint8)
    p1 = (120, 180)
    p2 = (10, 12)
    p3 = (40, 70)
    p4 = (90, 100)
    pointsMat = np.array([p1, p2, p3, p4])
    k, b = get_linear_fit_k_b(pointsMat)

    x1 = 10
    y1 = k * x1 + b
    x2 = 120
    y2 = k * x2 + b

    cv.line(imgColor, (x1, y1), (x2, y2), (0, 255, 0), thickness=1)
    imgColor[180,120] = (0,0,255)
    imgColor[12,10] = (0,0,255)
    imgColor[70,40] = (0,0,255)
    imgColor[100,90] = (0,0,255)
    cv.imshow("imgColor", imgColor)
    cv.waitKey(0)
